package com.obas.business.device.view
{
//	import com.as3xls.xls.ExcelFile;
//	import com.as3xls.xls.Sheet;
	import com.ease.common.vo.Pagination;
	import com.ease.framework.CommandCompletionEvent;
	import com.ease.component.managers.ConfirmHelper;
	import com.ease.component.managers.ErrorManager;
	import com.ease.component.managers.ProgressManager;
//	import com.obas.constants.StringConstants;
	import com.obas.common.util.ResourceUtil;
	import com.obas.business.device.dialog.CreateDeviceDialog;
	import com.obas.business.device.event.DeviceManagementEvent;
	import com.obas.business.topo.event.TopoVisualizationEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.system.System;
	import flash.ui.Keyboard;
	import flash.utils.ByteArray;

	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;
	import mx.events.CloseEvent;
	import mx.events.MenuEvent;
	import mx.managers.PopUpManager;
	import mx.utils.ObjectUtil;
	import mx.utils.StringUtil;

//   [Event(name="{com.pktech.inventory.lib.events.GridOperationEvent.REQUEST_ID}",
//      type="com.pktech.inventory.lib.events.GridOperationEvent")]
//
//   [Event(name="{com.pktech.core.events.ViewOperationEvent.REQUEST_ID}",
//         type="com.pktech.core.events.ViewOperationEvent")]
//
//   [Event(name="{com.pktech.inventory.lib.events.DataRefreshEvent.REQUEST_ID}",
//         type="com.pktech.inventory.lib.events.DataRefreshEvent")]
//   
//   [Event(name="{com.pktech.inventory.lib.events.RequestFormEvent.REQUEST_ID}",
//      type="com.pktech.inventory.lib.events.RequestFormEvent")]
//   
//   [Event(name="{com.pktech.inventory.lib.events.EntityOperationEvent.REQUEST_ID}",
//      type="com.pktech.inventory.lib.events.EntityOperationEvent")]

	
	[Event(name="{com.obas.business.topo.event.TopoVisualizationEvent.REQUEST_ID}",
         type="com.obas.business.topo.event.TopoVisualizationEvent")]
	[Event(name="{com.obas.business.device.event.DeviceManagementEvent.REQUEST_ID}", type="com.obas.business.device.event.DeviceManagementEvent")]

	public class DeviceManagementMediator extends EventDispatcher
	{
//      private var listUtil:ListDataUtil = new ListDataUtil(keyFunction);

		private var metaEntityTypeId:Number=0;

		private var entityTypeIds:ArrayCollection;

//      private var _gridpage:Gridpage;

		private var _view:DeviceManagementView;

		[InjectableView]
		/**
		 * The mediator's view.
		 */
		public function get view():DeviceManagementView
		{
			return _view;
		}

		public function set view(value:DeviceManagementView):void
		{
			_view=value;
			init();
		}

		private function init():void
		{
			appendEventListeners();

			if (view.metaEntityTypeId)
			{
				metaEntityTypeId=view.metaEntityTypeId;
			}

			if (view.entityTypeIds)
			{
				entityTypeIds=new ArrayCollection(view.entityTypeIds);
			}

//         ProgressManager.showProgress(_view, ProgressManager.LOADING_SPINNER);

//         if (_view.gridpageId > 0) {
//            dispatchEvent(new GridOperationEvent([_view.gridpageId]));
//         }
//         else if (!StringUtils.isNullorEmpty(_view.gridpageCode)) {
//            dispatchEvent(new GridOperationEvent([_view.gridpageCode], GridOperationEvent.TYPE_GET_GRIDPAGE_BY_CODE));
//         }
//         else if (view.entityTypeId > 0) {
//            dispatchEvent(new GridOperationEvent([_view.entityTypeId], GridOperationEvent.TYPE_GET_GRIDPAGE_BY_ENTITY_TYPE));
//         }
//         else if (_view.attributeTypeId > 0 || _view.metaAttributeTypeId > 0) {
//            dispatchEvent(new RequestFormEvent([_view.metaAttributeTypeId, _view.attributeTypeId], RequestFormEvent.FIND_GENERAL_QUERY_PARAM));
//         }
//         else {
//            _view.autoLoadFlag = false;
//            _view.commonQueryBarBox.visible = _view.commonQueryBarBox.includeInLayout = true;
//            dispatchEvent(new GridOperationEvent([null],GridOperationEvent.TYPE_GET_META_ENTITY_TYPE));
//            dispatchEvent(new GridOperationEvent([null],GridOperationEvent.TYPE_GET_ENTITY_TYPES));
//         }
		}
		private function onViewTopo(e:*):void
		{
			var topoVisualizationEvent:TopoVisualizationEvent=new TopoVisualizationEvent(TopoVisualizationEvent.OPERATION_VIEW_NETWORK_TOPOLOGY);
			topoVisualizationEvent.deviceId=_view.datagrid.selectedItem.id;
			dispatchEvent(topoVisualizationEvent);
		}

		private function onCreateDevice(e:*):void
		{

			var dialog:CreateDeviceDialog=PopUpManager.createPopUp(view.root, CreateDeviceDialog, true) as CreateDeviceDialog;
//		  dialog.parentProject = view.navTree.selectedItem as Node;
			PopUpManager.centerPopUp(dialog);

		}

		private function onRemoveDevice(e:*):void
		{
			ConfirmHelper.showConfirmDialog("删除", "确定删除？", doRemoveDevice);
		}

		private function doRemoveDevice(e:CloseEvent):void
		{
			if (e.detail == Alert.YES)
			{
				if (_view.datagrid.selectedItems && view.datagrid.selectedItems.length > 0)
				{
					var deviceManagementEvent:DeviceManagementEvent=new DeviceManagementEvent(DeviceManagementEvent.OPERATION_REMOVE);
					deviceManagementEvent.devices=new ArrayCollection(_view.datagrid.selectedItems);
					dispatchEvent(deviceManagementEvent);
				}
//  			  dispatchEvent(new DeviceManagementEvent([view.navTree.selectedItem.entity, view.navTree.selectedItem], ItestOperationEvent.DELETE_PROJECT));
			}
			;
		}

		private function onUpdateDevice(e:*):void
		{
//		  var dialog:CreateDeviceDialog = PopUpManager.createPopUp(view.root, CreateDeviceDialog, true) as CreateDeviceDialog;
//		  var sltNode:Node = view.navTree.selectedItem as Node;
//		  dialog.sceName.text = sltNode.name;
//		  dialog.actionType = ITestLibConstants.ACTION_UPDATE;
//		  dialog.systemScenario = sltNode.entity as SystemScenario;
//		  //         dialog.parentProject = view.navTree.selectedItem as Node;
//		  PopUpManager.centerPopUp(dialog);
		}



		private function onQueryBtn(e:*=null):void
		{
			ProgressManager.showProgress(_view.datagrid, ProgressManager.LOADING_SPINNER);
			_view.dataProvider = null;
			var deviceManagementEvent:DeviceManagementEvent=new DeviceManagementEvent(DeviceManagementEvent.OPERATION_QUERY);
			var pagination:Pagination=new Pagination();
			pagination.index=1;
			pagination.size=100;
			deviceManagementEvent.pagination=pagination;
			dispatchEvent(deviceManagementEvent);
		}
		
		private function onRetrieveBtnDevice(e:*=null):void
		{
			ProgressManager.hideProgress(view.datagrid);
			if (_view.datagrid.selectedItems && view.datagrid.selectedItems.length > 0)
			{
				var deviceManagementEvent:DeviceManagementEvent=new DeviceManagementEvent(DeviceManagementEvent.OPERATION_RETRIEVE_USERMACADDRESS);
				deviceManagementEvent.devices=new ArrayCollection(_view.datagrid.selectedItems);
				dispatchEvent(deviceManagementEvent);
			}
		}
				
		private function appendEventListeners():void
		{
			_view.queryBtn.addEventListener(MouseEvent.CLICK, onQueryBtn);
			_view.createBtn.addEventListener(MouseEvent.CLICK, onCreateDevice);
			_view.updateBtn.addEventListener(MouseEvent.CLICK, onUpdateDevice);
			_view.removeBtn.addEventListener(MouseEvent.CLICK, onRemoveDevice);
			_view.retrieveBtn.addEventListener(MouseEvent.CLICK, onRetrieveBtnDevice);
			_view.viewTopoBtn.addEventListener(MouseEvent.CLICK, onViewTopo);
			

//         if (!_view.toolbar.hasEventListener(ToolbarEvent.TYPE_CLICK)) {
//            _view.toolbar.addEventListener(ToolbarEvent.TYPE_CLICK, onToolBarEvent);
//            _view.list.addEventListener(ListQueryEvent.TYPE_QUERY, onListQuery);
//            _view.metaEntityTypeInput.addEventListener(DropdownEditInput.ITEM_SELECTED, metaEntityTypeChangeHandler);
//            _view.entityTypeInput.addEventListener(DropdownEditInput.ITEM_SELECTED, entityTypeChangeHandler);
//            _view.entityTypeInput.addEventListener(Event.CHANGE, entityTypeInput_change);
//            _view.list.addEventListener(InventoryLibConstants.MENU_ENTITY_CLICK, onMenuClick);
//            _view.list.addEventListener(InventoryLibConstants.MENU_COPY_CLICK, onCopyClick);
//            _view.form.addEventListener(KeyboardEvent.KEY_DOWN, onFormKeyDown);
//         }
		}

//      [ResponseHandler("{com.pktech.inventory.lib.events.RequestFormEvent.RETURN_ID}")]
//      public function onRequestFormEvent(event:CommandCompletionEvent):void {
//         if (event.error) {
//            ErrorManager.showErrorMessage(ResourceUtil.getErrorString(StringConstants.FORM_PAGE_ERROR, event.error));
//            return ;
//         }
//         var request:RequestFormEvent = event.request as RequestFormEvent;
//         if(RequestFormEvent.FIND_GENERAL_QUERY_PARAM == request.actionType) {
//            var generalQueryParam:GeneralQueryParam = event.result as GeneralQueryParam;
//            if(!generalQueryParam) {
//               dispatchEvent(new GridOperationEvent([_view.attributeTypeId], GridOperationEvent.TYPE_GET_GRIDPAGE_BY_ATTRIBUTE));
//               return;
//            }
//            var etnityTypes:ArrayCollection = generalQueryParam.entityTypes;
//            
//            //如果entityType只有一个
//            if(etnityTypes.length == 1) {
//               dispatchEvent(new GridOperationEvent([etnityTypes.getItemAt(0).id], GridOperationEvent.TYPE_GET_GRIDPAGE_BY_ENTITY_TYPE));
//               return;
//            }
//            
//            var tempArr:ArrayCollection = new ArrayCollection();
//            for each (var tempET:EntityType in etnityTypes) {
//               tempArr.addItem(tempET.id);
//            }
//            entityTypeIds = tempArr;
//            metaEntityTypeId = generalQueryParam.metaEntityType.id;
//            
//            dispatchEvent(new GridOperationEvent([null],GridOperationEvent.TYPE_GET_META_ENTITY_TYPE));
//            dispatchEvent(new GridOperationEvent([null],GridOperationEvent.TYPE_GET_ENTITY_TYPES));
//            dispatchEvent(new GridOperationEvent([metaEntityTypeId], GridOperationEvent.TYPE_GET_GRIDPAGE_BY_META_ENTITY_TYPE));
//            _view.commonQueryBarBox.visible = _view.commonQueryBarBox.includeInLayout = true;
//         }
//         else if(RequestFormEvent.TYPE_GRAFT_EVENT == request.actionType){
//            ProgressManager.hideProgress(view);
//            var param : BulkChangeResultParam = event.result as BulkChangeResultParam;
//            var errorMsg : String = "操作完成.";
//            if(param && param.errorMessage){
//               errorMsg = param.errorMessage;
//            }
//            ConfirmHelper.showInformationDialog("提示", errorMsg);
//         }
//      }
//
//     [ResponseHandler("{com.pktech.inventory.lib.events.EntityOperationEvent.RETURN_ID}")]
//     public function onEntityOperationEvent(event:CommandCompletionEvent):void {
//        if (event.error) {
//           ErrorManager.showErrorMessage(ResourceUtil.getErrorString(StringConstants.GRID_PAGE_ERROR, event.error));
//           return ;
//        }
//        var request:EntityOperationEvent = event.request as EntityOperationEvent;
//        var requestParam:Object = request.spec;
//        if(EntityOperationEvent.TYPE_SCATTER_HIGHER_TIMESLOT == request.actionType) {
//           ConfirmHelper.showWarningDialog("", "高阶时隙划分成功，请查看" + (requestParam.entity as Entity).name + "的[关联信息-时隙]");   
//        }
//        else if (EntityOperationEvent.TYPE_SCATTER_LOWER_TIMESLOT == request.actionType) {
//           ConfirmHelper.showWarningDialog("", "低阶时隙划分成功，请查看" + (requestParam.entity as Entity).name + "的[关联信息-时隙]");
//        }
//        else if (EntityOperationEvent.TYPE_REMOVE_TIMESLOTS == request.actionType) {
//            ConfirmHelper.showWarningDialog("", "时隙删除成功，请查看" + (requestParam.entity as Entity).name + "的[关联信息-时隙]");
//        }
//     }
//
//      private function entityTypeInput_change(event:Event):void {
//         if (_view.attributeTypeId > 0 && _view.entityTypeInput.text == "") {
//            dispatchEvent(new GridOperationEvent([metaEntityTypeId], GridOperationEvent.TYPE_GET_GRIDPAGE_BY_META_ENTITY_TYPE));
//         }
//      }
//
//      private function onMenuClick(event:MenuEvent):void {
//         event.stopImmediatePropagation();
//         var param:* = event.item.data;
//         param.entityTypeId = _gridpage.entityTypeId;
//         if (!_view.list.datagrid.selectedItem) {
//            return;
//         }
//         param.entity = _view.list.datagrid.selectedItem._entity;
//         if (0 == param.entityTypeId && null != param.entity as Entity) {
//            param.entityTypeId = param.entity.entityType.id;
//         }
//         param.entityType = _view.list.datagrid.selectedItem._entity.entityType;
//         param.source = _gridpage.id;
//         param.context = view.context;
//         param.items = new ArrayCollection(_view.list.datagrid.selectedItems);
//
//         switch (param.actionType) {
//            case "refreshCodeDegree":
//               var codeRanges:ArrayCollection = new ArrayCollection();
//               if (null != _view.list.datagrid.selectedItems && 0 < _view.list.datagrid.selectedItems.length) {
//                  for each(var item:Object in _view.list.selectedItems) {
//                     codeRanges.addItem(item._entity);
//                  }
//               }
//               param.codeRanges = codeRanges;
//               dispatchEvent(new GridOperationEvent(param, GridOperationEvent.TYPE_REFRESH_CODEDEGREE));
//               break;
//         case "scatterHigherTimeslot":
//            dispatchEvent(new EntityOperationEvent(param, EntityOperationEvent.TYPE_SCATTER_HIGHER_TIMESLOT));
//            break;
//         case "scatterLowerTimeslot":
//            param.mappingMode = 10;
//            dispatchEvent(new EntityOperationEvent(param, EntityOperationEvent.TYPE_SCATTER_LOWER_TIMESLOT));
//            break;
//         case "removeTimeslots":
//            dispatchEvent(new EntityOperationEvent(param, EntityOperationEvent.TYPE_REMOVE_TIMESLOTS));
//            break;
//         case "codeLinkQuery":
//            param.queryEntity = param.entity;
//            dispatchEvent(new ViewOperationEvent([param.targetView], param));
//            break;
//         default:
//            dispatchEvent(new ViewOperationEvent([param.targetView], param));
//            break;
//         }
//      }
//
//      protected function entityTypeChangeHandler(event:Event):void {
//         ProgressManager.showProgress(_view, ProgressManager.LOADING_SPINNER);
//         dispatchEvent(new GridOperationEvent([_view.entityTypeInput.currentValue], GridOperationEvent.TYPE_GET_GRIDPAGE_BY_ENTITY_TYPE));
//      }
//
//      protected function metaEntityTypeChangeHandler(event:Event):void {
//         ProgressManager.showProgress(_view, ProgressManager.LOADING_SPINNER);
//         dispatchEvent(new GridOperationEvent([_view.metaEntityTypeInput.currentValue], GridOperationEvent.TYPE_GET_GRIDPAGE_BY_META_ENTITY_TYPE));
//      }
//
//      private function onFormKeyDown(e:KeyboardEvent):void {
//         if (e.keyCode == Keyboard.ENTER) {
//            _view.paginationParam.pagination.index = 1;
//            getResult(_view.paginationParam, _gridpage.id, true);
//         }
//      }
//      
//      private function onListQuery(event:ListQueryEvent):void {
//         if ("inventory" != _view.uiType) {
//            return;
//         }
//         var paginationParam:PaginationMapParameter = _view.paginationParam;
//         paginationParam.pagination = event.spec[0];
//         paginationParam.ordering = event.spec[1];
//         getResult(paginationParam,_gridpage.id, true);
//      }
//      
//      private function getResult(paginationParam:PaginationMapParameter,gridPageId:Number,paginationed:Boolean):void {
//         ProgressManager.showProgress(_view, ProgressManager.LOADING_SPINNER);
//         if (null != view.customizeGetResult) {
//            view.customizeGetResult(view, paginationParam, gridPageId, paginationed);
//         }
//         else {
//            dispatchEvent(new GridOperationEvent([paginationParam, gridPageId, paginationed], GridOperationEvent.TYPE_GET_RESULT));
//         }
//      }
//
//      private function onToolBarEvent(event:ToolbarEvent):void {
//         if ("inventory" != _view.uiType || !event.spec) {
//            return;
//         }
//         var param:* = ObjectUtil.copy(event.spec);
//         var requestParam:Object = new Object();
//         
//         var type:String = param.type? param.type : param.actionType;
//         switch (type) {
//            case InventoryLibConstants.ACTION_QUERY:
//               _view.paginationParam.pagination.index = 1;
//               getResult(_view.paginationParam, _gridpage.id, true);
//               return;
//            case InventoryLibConstants.ACTION_CLEAR:
//               if (_view.form){
//                  _view.form.clear();
//               }
//               return;
//            case InventoryLibConstants.EXPORT_CURRENT:
//            case InventoryLibConstants.EXPORT_SELECTED:
//            case InventoryLibConstants.EXPORT_ALL:
//               if (param.hasOwnProperty("template")) {
//                  exportToExcelByTemplate(param);
//               } else {
//                  exportToExcel(param.type);
//               }
//               return;
//            case "scatterHigherTimeslot":
//               requestParam.circuit = param.circuit;
//               dispatchEvent(new EntityOperationEvent(requestParam, EntityOperationEvent.TYPE_SCATTER_HIGHER_TIMESLOT));
//               return;
//            case "scatterLowerTimeslot":
//               requestParam.circuit = param.circuit;
//               requestParam.mappingMode = 10;
//               dispatchEvent(new EntityOperationEvent(requestParam, EntityOperationEvent.TYPE_SCATTER_LOWER_TIMESLOT));
//               return;
//            case "removeTimeslots":
//               requestParam.circuit = param.circuit;
//               dispatchEvent(new EntityOperationEvent(requestParam, EntityOperationEvent.TYPE_REMOVE_TIMESLOTS));
//               return;
//            case InventoryLibConstants.ACTION_START_PROCESS:
//               if(null == _view.list.datagrid.selectedItems || _view.list.datagrid.selectedItems.length != 1){
//                  ConfirmHelper.showWarningDialog("", "请选择一条!");
//                  return;
//               }
//                
//               var order:Order =  _view.list.datagrid.selectedItem._entity;
//               if (null != order) {
////                  if (order.lifecycleStatus == 3) {
////                     ConfirmHelper.showWarningDialog("", "该工单正在排队，不能人工启动!");
////                     return;
////                  }
//                  ProgressManager.showProgress(_view, ProgressManager.LOADING_SPINNER);
//                  requestParam.orderId = order.id;
//                  dispatchEvent(new GridOperationEvent(requestParam, GridOperationEvent.TYPE_START_PROCESS));
//               }
//               return;
//            case InventoryLibConstants.ACTION_CREATE:
//               param.title = ResourceUtil.getString(StringConstants.GENERAL_ADD) + _gridpage.name;
//               break;
//            case InventoryLibConstants.ACTION_TOPO_DISPLAY:
//            case InventoryLibConstants.ACTION_UPDATE:
//            case InventoryLibConstants.ACTION_VIEW:
//               if (_view.list.datagrid.selectedItems.length != 1) {
//                  ConfirmHelper.showWarningDialog("", ResourceUtil.getString(StringConstants.GENERAL_SELECT_MODIFY_RECORD));
//                  return;
//               }
//               param.title = ResourceUtil.getString(StringConstants.GENERAL_MODIFY) + _gridpage.name;
//               param.entity = _view.list.datagrid.selectedItem._entity;
//               if (param.entity is Entity) {
//                  param.entityType = (_view.list.datagrid.selectedItem._entity as Entity).entityType;
//               }
//               break;
//            case InventoryLibConstants.ACTION_DELETE:
//               var items:Array = _view.list.datagrid.selectedItems;
//               if (!items || items.length == 0) {
//                  ConfirmHelper.showWarningDialog("", ResourceUtil.getString(StringConstants.GENERAL_SELECT_DELETE_RECORDS));
//                  return;
//               }
//               param.title = ResourceUtil.getString(StringConstants.GENERAL_REMOVE) + _gridpage.name;
//               param.items = new ArrayCollection(items);
//               break;
//            case InventoryLibConstants.ACTION_BATCH_UPDATE:
//               if (_view.list.datagrid.selectedItems.length == 0) {
//                  ConfirmHelper.showWarningDialog("", ResourceUtil.getString(StringConstants.GENERAL_SELECT_BATCHUPDATE_MODIFY_RECORDS));
//                  return;
//               }
//               param.title = ResourceUtil.getString(StringConstants.GENERAL_BATCH_UPDATE) + _gridpage.name;
//               var _selectedItemsTemp:ArrayCollection = new ArrayCollection();
//               for each (var objT:Object in _view.list.datagrid.selectedItems) {
//                  _selectedItemsTemp.addItem(objT._entity);
//               }
//               param.entity = _selectedItemsTemp;
//               break;
//            case InventoryLibConstants.ACTION_IMPORT:
//               param.title = ResourceUtil.getString(StringConstants.GENERAL_IMPORT) + _gridpage.name;
//               break;
//            case InventoryLibConstants.ACTION_RELATION_ENTITY:
//               var items2:Array = _view.list.datagrid.selectedItems;
//               if (!items2 || items2.length == 0) {
//                  ConfirmHelper.showWarningDialog("", ResourceUtil.getString(StringConstants.GENERAL_SELECT_REALTE_RECORD));
//                  return;
//               }
//               param.title = ResourceUtil.getString(StringConstants.GENERAL_RELATION_ENTITY) + _gridpage.name;
//               param.entity = new ArrayCollection(items2);
//               break;
//            case InventoryLibConstants.ACTION_CODE_RELATION:
//               param.title = ResourceUtil.getString( StringConstants.GENERAL_ENTITY_IMPORT_TEMPLATE_MANAGE_ADD ) 
//                                       + ResourceUtil.getString( StringConstants.GENERAL_CODE_RELATION_ADD_ENTITY );
//               break;
//            case InventoryLibConstants.ACTION_LINK_RELATION:
//               if (_view.list.datagrid.selectedItems.length > 1) {
//                  ConfirmHelper.showWarningDialog("", ResourceUtil.getString(StringConstants.GENERAL_SELECT_MODIFY_RECORD));
//                  return;
//               } else if (_view.list.datagrid.selectedItems.length == 1) {
//                  param.title = _gridpage.name + ResourceUtil.getString( StringConstants.GENERAL_LINK_RELATION_ADD_ENTITY );
//                  param.entity = _view.list.datagrid.selectedItem._entity;
//                  param.entityType = (_view.list.datagrid.selectedItem._entity as Entity).entityType;
//                  param.metaEntityTypeId = (_view.list.datagrid.selectedItem._entity as Entity).entityType.metaEntityTypeId;
//               } else {
//                  param.title = ResourceUtil.getString( StringConstants.GENERAL_LINK_RELATION_ADD_ENTITY ) + _gridpage.name;
//                  if(this._gridpage.entityType) {
//                     param.entityType = this._gridpage.entityType;
//                     param.metaEntityTypeId = this._gridpage.entityType.metaEntityTypeId;
//                  } else {
//                     param.metaEntityTypeId = _view.metaEntityTypeInput.currentValue;
//                  }
//               }
//               break;
//            case InventoryLibConstants.CREATE_CODE_BY_RANGE:
//               if (_view.list.datagrid.selectedItems.length != 1) {
//                  ConfirmHelper.showWarningDialog("", ResourceUtil.getString(StringConstants.GENERAL_SELECT_MODIFY_RECORD));
//                  return;
//               }
//               
//               param.title = _gridpage.name;
//               param.entity = _view.list.datagrid.selectedItem._entity;
//               break;
//            case "bulkChange":
//               var bulkitems:Array = _view.list.datagrid.selectedItems;
//               if (!bulkitems || bulkitems.length == 0) {
//                  ConfirmHelper.showWarningDialog("提示", "请选择一个工程.");
//                  return;
//               }
//               if(param.hasOwnProperty("projectAction")){
//                  
//                  switch(param.projectAction )
//                  {
//                     case BulkChangeEntity.FINISH:
//                     case BulkChangeEntity.FORCEFINISH:
//                     {
//                        if(bulkitems.length > 1){
//                           ConfirmHelper.showWarningDialog("提示", "请选择一个工程.");
//                           return;
//                        }
//                        var bulkChangeEntity : BulkChangeEntity = new BulkChangeEntity();
//                        bulkChangeEntity.projectId = bulkitems[0]._entity.id;
//                        bulkChangeEntity.lockType = param.projectAction;
//                        ProgressManager.showProgress(view,ProgressManager.LOADING_SPINNER);
//                        dispatchEvent(new RequestFormEvent([bulkChangeEntity], RequestFormEvent.TYPE_GRAFT_EVENT));
//                        return;
//                     }
//                  }
//               }
//               
//              param.projects = new ArrayCollection(bulkitems);
//              param.criteria = "projectId=" + param.projects[0]._entity.id+ ";areaId="+param.projects[0]._entity.areaId;
//               break;
//            }
//            if (_gridpage.entityTypeId > 0) {
//              param.entityTypeId = _gridpage.entityTypeId;
//            }
//            else if (_view.list.datagrid.selectedItem) {
//                 var entity:* = _view.list.datagrid.selectedItem._entity;
//                 if (entity is Entity) {
//                    param.entityTypeId = entity.entityTypeId;
//                 }
//            }
//            param.source = param.gridpageId = _gridpage.id;
//            param.context = view.context;
//            param.defaultValue = view.defaultValue? ObjectUtil.copy(view.defaultValue) : view.form.defaultValue? ObjectUtil.copy(view.form.defaultValue) : new Object();
//            
//            dispatchEvent(new ViewOperationEvent([param.targetView], param));
//            param = null;
//      }
//      
//      private function exportToExcelByTemplate(param:Object):void {
//         var excelParam:ExportExcelParam = new ExportExcelParam();
//         if (param.type == InventoryLibConstants.EXPORT_ALL) {
//            excelParam.exportAll = true;
//         }
//         else if (param.type == InventoryLibConstants.EXPORT_SELECTED) {
//            excelParam.exportAll = false;
//            excelParam.numbers = new ArrayCollection();
//            var items:Array = _view.list.datagrid.selectedItems;
//            for each (var item:* in items) {
//               excelParam.numbers.addItem(item._entity.id);
//            }
//         }
//         else {
//            excelParam.exportAll = false;
//            excelParam.pageCount = _view.paginationParam.pageCount;
//         }
//         excelParam.fileName = this._gridpage.name;
//         excelParam.entityTemplate = param.template as EntityTemplate;
//         ProgressManager.showProgress(view);
//         dispatchEvent(new GridOperationEvent([_view.paginationParam,_gridpage.id,excelParam],GridOperationEvent.TYPE_GET_URL));
//      }
//
//      private function exportToExcel(type:String):void {
//         if (type == InventoryLibConstants.EXPORT_ALL) {
//            var exportParam:ExportExcelParam = new ExportExcelParam();
//            exportParam.exportAll = true;
//            ProgressManager.showProgress(view);
//            dispatchEvent(new GridOperationEvent([_view.paginationParam,_gridpage.id,exportParam],GridOperationEvent.TYPE_GET_URL));
//         }
//         else {
//            var sheet:Sheet = new Sheet();
//            var columns:Array = _view.list.datagrid.columns;
//            var datas:ArrayCollection = type == InventoryLibConstants.EXPORT_CURRENT?
//               _view.list.dataProvider : new ArrayCollection(_view.list.datagrid.selectedItems);
//            if (datas.length > 0){
//               sheet.resize(datas.length + 1, columns.length);
//               for (var ii:int = 1; ii < columns.length; ii++) {
//                  var column:AdvancedDataGridColumn = columns[ii];
//                  sheet.setCell(0, ii - 1, column.headerText);
//               }
//               for (ii = 1; ii < columns.length; ii++) {
//                  column = columns[ii];
//                  for (var jj:int = 0; jj < datas.length; jj++) {
//                     var colData:Object = datas.getItemAt(jj);
//                     sheet.setCell(jj + 1, ii - 1, StringUtil.trim(column.itemToLabel(colData)));
//                  }
//               }
//               var xls:ExcelFile = new ExcelFile();
//               xls.sheets.addItem(sheet);
//               var bytes:ByteArray = xls.saveToByteArray();
//               FileUtil.getFileReference().save(bytes, _gridpage.name + ".xls");
//            }
//         }
//      }
//
//      [ResponseHandler("{com.pktech.inventory.lib.events.GridOperationEvent.RETURN_ID}")]
//      public function onGridOperationEvent(event:CommandCompletionEvent):void {
//         ProgressManager.hideProgress(_view);
//         var request:GridOperationEvent = event.request as GridOperationEvent;
//         if (event.error) {
//            ErrorManager.showErrorMessage(
//               ResourceUtil.getErrorString(StringConstants.GRID_PAGE_ERROR, event.error));
//            return;
//         }
//         switch (request.actionType) {
//            case GridOperationEvent.TYPE_GET_GRIDPAGE:
//            case GridOperationEvent.TYPE_GET_GRIDPAGE_BY_CODE:
//            case GridOperationEvent.TYPE_GET_GRIDPAGE_BY_META_ENTITY_TYPE:
//            case GridOperationEvent.TYPE_GET_GRIDPAGE_BY_ENTITY_TYPE:
//            case GridOperationEvent.TYPE_GET_GRIDPAGE_BY_ATTRIBUTE:
//               _view.mainBox.visible = _view.mainBox.includeInLayout = event.result != null;
//               if (event.result) {
//                  _gridpage = event.result as Gridpage;
//                  _view.gridpage = _gridpage;
//                  _view.label = _gridpage.name+" ";
//                  refreshToolBar();
//                  refreshForm();
//                  refreshList();
//                  if (_view.exportFlag && 0 < _gridpage.entityTypeId) {
//                     //得到该entityType对应的导出模板
//                     dispatchEvent(new GridOperationEvent([_gridpage.entityTypeId,EntityTemplateType.InventoryImporting],GridOperationEvent.TYPE_ENTITY_TEMPLATE_BY_ENTITYTYPE_ENTITYTEMPLATETYPE));
//                  }
//               }
//               if (_view.autoLoadFlag && _gridpage) {
//                  var paginationParam:PaginationMapParameter = new PaginationMapParameter();
//                  paginationParam.delegateParameters = new Object();
//                  paginationParam.pagination = view.list.pagination;
//                  paginationParam.ordering = view.list.ordering;
//                  paginationParam.appendCriteria = view.criteria;
//                  if (!paginationParam.appendCriteria && view.defaultValue) {
//                     for (var prop:String in view.defaultValue) {
//                        paginationParam.appendCriteria += prop + "=" + view.defaultValue[prop] + ";";
//                     }
//                  }
//                  view.list.callLater(getResult, [view.paginationParam, _gridpage.id, true]);
//               }
//               break;
//            case GridOperationEvent.TYPE_ENTITY_TEMPLATE_BY_ENTITYTYPE_ENTITYTEMPLATETYPE:
//               if(null == event.result || (event.result as ArrayCollection).length == 0 ){
//                  return;
//               }
//               
//               for each(var tempTemplate:EntityTemplate in event.result) {
//                  var tempBtn:CoolButton = new CoolButton();
//                  tempBtn.name = "模板:" + tempTemplate.name;
//                  tempBtn.tooltip = tempTemplate.name;
//                  tempBtn.enable = tempBtn.visible =true;
//                  tempBtn.parameterMap = new Object();
//                  tempBtn.parameterMap.template =  tempTemplate;
//                  _view.export.children.addItem(tempBtn);
//               }
//               break;
//            case GridOperationEvent.TYPE_GET_RESULT:
//               ProgressManager.hideProgress(_view.list);
//               var pagination:Pagination = event.result as Pagination;
//               _view.list.pagination = pagination;
//
//               var helper:DataRefreshHelper = new DataRefreshHelper();
//               helper.context = _view.context;
//               helper.data = pagination.items;
//               dispatchEvent(new DataRefreshEvent(helper));
//               break;
//            case GridOperationEvent.TYPE_GET_META_ENTITY_TYPE:
//               refreshMetaEntityList(event.result as ArrayCollection);
//               break;
//            case GridOperationEvent.TYPE_GET_ENTITY_TYPE:
//               refreshEntityList(event.result as ArrayCollection);
//               break;
//            case GridOperationEvent.TYPE_GET_ENTITY_TYPES:
//               refreshEntityList(event.result as ArrayCollection);
//               break;
//            case GridOperationEvent.TYPE_GET_MAP_BY_ENTITIES:
//               var dest:ArrayCollection = event.result as ArrayCollection;
//               listUtil.addOrUpdateItems(_view.list.dataProvider.source, dest.source, true);
//               _view.list.dataProvider.refresh();
//               if (_view.list.dataProvider && _view.list.dataProvider.length > 0) {
//                  _view.list.datagrid.selectedItems = _view.list.datagrid.selectedItems;
//               }
//               helper = new DataRefreshHelper();
//               helper.context = _view.context;
//               helper.data = dest;
//               dispatchEvent(new DataRefreshEvent(helper, DataRefreshEvent.TYPE_ADD_UPDATE));
//               break;
//            case GridOperationEvent.TYPE_GET_URL:
//               var file_url:String = String(event.result);
//               navigateToURL(new URLRequest(file_url), "_blank");
//               break;
//         case GridOperationEvent.TYPE_GET_META_ENTITY_TYPE_BY_ID:
//            var metaEntityType:MetaEntityType = event.result as MetaEntityType;
//            refreshMetaEntity(metaEntityType);
//            break;
//         case GridOperationEvent.TYPE_REFRESH_CODEDEGREE:
//            ConfirmHelper.showWarningDialog("", "码号等级刷新成功！");
//            break;
//         case GridOperationEvent.TYPE_START_PROCESS:
//            ConfirmHelper.showWarningDialog("", "已经在后台启动流程！请到待办工单中查看是否启动成功。");
//            _view.paginationParam.pagination.index = 1;
//            getResult(_view.paginationParam, _gridpage.id, true);
//            break;
//         }
//      }
//      
//      private function onCopyClick(e:*):void {
//         if (null != _view.list.selectedItems && 0 < _view.list.selectedItems.length) {
//            var itemStr:String = "";
//            var datas:ArrayCollection = new ArrayCollection(_view.list.selectedItems);
//            var columns:Array = _view.list.datagrid.columns;
//            for (var jj:int = 0; jj < datas.length; jj++) {
//               var colData:Object = datas.getItemAt(jj);
//               for (var ii:int = 1; ii < columns.length; ii++) {
//                  var column:AdvancedDataGridColumn = columns[ii];
//                  itemStr += StringUtil.trim(column.itemToLabel(colData)) + " \t";
//               }
//               itemStr += "\n";
//            }
//            System.setClipboard(itemStr); 
//         }
//      }
//
//      private function refreshToolBar():void {
//         if (_gridpage && _gridpage.toolbar && _gridpage.toolbar.buttons) {
//            if (_view.leftButtons) {
//               _view.toolbar.leftButtonList = _view.leftButtons;
//            }
//            else {
//               _view.toolbar.leftButtonList = _gridpage.toolbar.buttons;
//            }
//         }
//      }
//
//      private function refreshForm():void {
//         if (_gridpage && _gridpage.criteriaTemplate) {
//            if(_gridpage.criteriaTemplate.attributeTemplateId) {
//               _view.form.relateAttributeTemplateId = _gridpage.criteriaTemplate.attributeTemplateId + "";
//            }
//            _view.form.entityTemplate = _gridpage.criteriaTemplate;
//         }
//         //为了通用查询添加此段逻辑。因为通用查询可能会在同一个页面刷新出多个gridpage，这个时候必须每次都吧查询条件置空，以免上个gridpage的查询条件影响下个gridpage
//         if (_view.form && _view.form.queryCriteria) {
//            _view.form.queryCriteria = new Object();
//            _view.form.refreshForm();
//         }
//      }
//
//      private function refreshList():void {
//         if (_gridpage && _gridpage.resultTemplate) {
//            _view.list.entityTemplate = _gridpage.resultTemplate;
//         }
//      }
//
//     private function refreshMetaEntity(value:MetaEntityType):void {
//        if (null != _view) {
//           _view.metaEntityTypeInput.currentValue = new String(value.id);
//           _view.metaEntityTypeInput.text = value.name;
//           _view.metaEntityTypeInput.dispatchEvent(new Event(DropdownEditInput.ITEM_SELECTED)); 
//        }
//     }
//
//     private function refreshDataProvider(dataProvider:ArrayCollection):void {
//        if (null != dataProvider) {
//           for each(var item:Object in dataProvider) {
//               item.name = item.name + "(" + item.code + ")";
//            }
//        }
//     }
//  
//      private function refreshMetaEntityList(value:ArrayCollection):void {
//         if (null != _view) {
//            refreshDataProvider(value);
//            _view.metaEntityTypeInput.listDataProvider = value;
//            if( metaEntityTypeId > 0) {
//               for each(var tempE:MetaEntityType in value) {
//                  if(metaEntityTypeId == tempE.id) {
//                     _view.metaEntityTypeInput.currentValue = new String(tempE.id);
//                     _view.metaEntityTypeInput.text = tempE.name;
//                     dispatchEvent(new GridOperationEvent([Object(tempE.id)], GridOperationEvent.TYPE_GET_ENTITY_TYPE));
//                     _view.metaEntityTypeInput.editable = false;
//                     break;
//                  }
//               }
//            }
//         }
//      }
//
//      private function refreshEntityList(value:ArrayCollection):void {
//         if (null != _view) {
//            refreshDataProvider(value);
//            if(null == entityTypeIds || entityTypeIds.length ==0 ){
//               _view.metaEntityTypeInput.nextListDataProvider = value;
//            } else {
//               var tempArr:ArrayCollection = new ArrayCollection();
//               for each(var tmp:EntityType in value) {
//                  if(entityTypeIds.getItemIndex(tmp.id) != -1)
//                     tempArr.addItem(tmp);
//               }
//               _view.metaEntityTypeInput.nextListDataProvider = tempArr;
//               if (null != _view.entityTypeInputCallback) {
//                  _view.metaEntityTypeInput.nextListDataProvider = _view.entityTypeInputCallback(_view.metaEntityTypeInput.nextListDataProvider);
//               }
//            }
//         }
//      }
//
//      [EventHandler("{com.pktech.inventory.lib.events.DataRefreshEvent.REQUEST_ID}")]
//      public function onDataRefreshEvent(event:DataRefreshEvent):void {
//         if (!_gridpage || _gridpage.id != event.spec.source) {
//            return;
//         }
//         switch (event.actionType) {
//            case DataRefreshEvent.TYPE_DELETE :
//               deleteItems(event.spec.data);
//               break;
//            case DataRefreshEvent.TYPE_ADD_UPDATE :
//               addOrUpdateItems(event.spec.data);
//               break;
//         }
//      }
//
//      private function keyFunction(item:*):String {
//         if (item._entity.hasOwnProperty("id")) {
//            return item._entity.id + "";
//         }
//         else if (item._entity.hasOwnProperty("ID")) {
//            return item._entity.ID + "";
//         }
//         else {
//            return item._entity + "";
//         }
//      }
//
//      private function deleteItems(items:ArrayCollection):void {
//         listUtil.removeItems(_view.list.dataProvider.source, items.source);
//         _view.list.dataProvider.refresh();
//         if (_view.list.dataProvider && _view.list.dataProvider.length > 0) {
//            _view.list.datagrid.selectedItems = _view.list.datagrid.selectedItems;
//         }
//      }
//
//      private function addOrUpdateItems(items:ArrayCollection):void {
//         dispatchEvent(new GridOperationEvent([items, _gridpage.id], GridOperationEvent.TYPE_GET_MAP_BY_ENTITIES));
//      }
//      
//      private function onRemoved(event:ObjectEvent):void {
//         if (event.object == this) {
//            _view.toolbar.removeEventListener(ToolbarEvent.TYPE_CLICK, onToolBarEvent);
//            _view.list.removeEventListener(ListQueryEvent.TYPE_QUERY, onListQuery);
//            _view.metaEntityTypeInput.removeEventListener(DropdownEditInput.ITEM_SELECTED,metaEntityTypeChangeHandler);
//            _view.entityTypeInput.removeEventListener(DropdownEditInput.ITEM_SELECTED, entityTypeChangeHandler);
//            _view.entityTypeInput.removeEventListener(Event.CHANGE, entityTypeInput_change);
//            _view.list.removeEventListener(InventoryLibConstants.MENU_ENTITY_CLICK, onMenuClick);
//            
//            ViewRegistry.instance.removeEventListener(ObjectEvent.OBJECT_REMOVED, onRemoved);
//            ViewRegistry.instance.addEventListener(ObjectEvent.OBJECT_ADDED, onAdded);
//         }
//      }
//      
//      private function onAdded(event:ObjectEvent):void {
//         if (event.object == this) {
//            appendEventListeners();
//            ViewRegistry.instance.addEventListener(ObjectEvent.OBJECT_REMOVED, onRemoved);
//            ViewRegistry.instance.removeEventListener(ObjectEvent.OBJECT_ADDED, onAdded);
//         }
//      }



		[ResponseHandler("{com.obas.business.device.event.DeviceManagementEvent.RETURN_ID}")]
		public function onDeviceManagementEvent(event:CommandCompletionEvent):void
		{

			var request:DeviceManagementEvent=event.request as DeviceManagementEvent;
			if (event.error)
			{
				ErrorManager.showErrorMessage(ResourceUtil.getErrorString("", event.error));
				return;
			}

			switch (request.actionType)
			{
				case DeviceManagementEvent.OPERATION_QUERY:
					ProgressManager.hideProgress(_view.datagrid);
					_view.dataProvider=(event.result as Pagination).items;
					break;
				case DeviceManagementEvent.OPERATION_REMOVE:
					onQueryBtn();
					break;
				case DeviceManagementEvent.OPERATION_RETRIEVE_USERMACADDRESS:
					ProgressManager.showProgress(view.datagrid);
					Alert.show("ok");
					break;

			}

		}
	}
}